using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Domain.Login.register.Login.Interface;
using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;
using imitateMacQQ.WebApi.Repository.EFCore.Model.LoginPhoneCode;
using Microsoft.EntityFrameworkCore;

namespace imitateMacQQ.WebApi.Domain.Login.register.Login.Service;

public class GetLoginCode : IGetLoginCode
{
    public async Task<Request<bool>> GetPhoneCode(string phone)
    {
        try
        {
            await using DataDbContext db = new DataDbContext();
            var time = DateTime.Now.AddMinutes(5);
            var code = GetCode();
            
            var info = await db.PhoneCodes.FirstOrDefaultAsync(e => e.Phone == phone);
            if (info is null)
            {
                db.PhoneCodes.Add(new PhoneCode()
                {
                    EndTime = time,
                    Phone = phone,
                    Code = code,
                    GetSum = 1
                });
            }
            else
            {
                ++info.GetSum;
                info.Code = code;
                if (info.GetSum > 5)
                    return Request<bool>.Ok(false, false, "每日最多请求5次！");
            }

            {
                //插入发送信息接口
            }

            await db.SaveChangesAsync();
            return Request<bool>.Ok(true);
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<bool>.Ok(false, false, ex.Message);
        }
    }

    public GetLoginCode(IConfiguration configuration, INLogHelper logHelper)
    {
        try
        {
            _length = int.Parse(configuration.GetSection("CodeLength").Value ?? "4");
        }
        catch (Exception ex)
        {
            logHelper.LogError(ex);
            _length = 4;
        }

        _logHelper = logHelper;
    }

    private readonly INLogHelper _logHelper;
    private readonly int _length;

    private string GetCode()
    {
        string res = string.Empty;
        var data = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        for (int i = 0; i < _length; i++)
        {
            Random r = new Random();
            res += data[r.Next(0, 10)].ToString();
        }

        return res;
    }
}